package com.steak.cloudscomsumeruser.controller;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.ribbon.proxy.annotation.Hystrix;
import com.steak.cloudscomsumeruser.client.OrderClient;
import com.steak.cloudscomsumeruser.domain.ClickVO;
import com.steak.cloudscomsumeruser.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private OrderClient orderClient;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * redis点赞
     * @param clickNum
     * @return
     */
    @GetMapping("/clickIt")
    public String clickIt(@RequestParam int clickNum){
        ClickVO clickVO = new ClickVO();
        redisTemplate.opsForValue().set("clickNum", String.valueOf(clickNum+1));
        String clickNums = redisTemplate.opsForValue().get("clickNum");
        return clickNums;
    }

    @GetMapping("/userInfo")
    public User userInfo(){
        User user = new User();
        user.setUsername("steak").setPassword("123456");
        return user;
    }

    /**
     * 降级有很多方式触发，例如目标服务不能正常提供服务，也可以自己定义，例如本服务出现异常或者其他，方法上的降级优先级最高
     * @return
     */
    @HystrixCommand(fallbackMethod = "fallback")
    @GetMapping("/getOrderInfo")
    public String getOrderInfo(){
        String orderInfo = orderClient.orderInfo();
        return orderInfo;
        //throw new RuntimeException("异常方式降级");haoler
    }

    public String fallback(){
        return "太过于拥挤";
    }
    /**
     * 默认降级方法
     * @return
     */
    public String defaultFallback(){
        return "默认的降级方法";
    }

    /**
     * 模拟权限验证,此处只是用参数，后面有时间再使用AOP或者其他权限框架
     * @param request
     * @return
     */
    @GetMapping("/adminOnly")
    public String auth(HttpServletRequest request){
        System.out.println(request.getParameter("token"));
        if (request.getParameter("token").equals("admin")){
            return "你好，管理员";
        }
        else {
            return "你没访问权限";
        }
    }



}
